package com.webserver.http;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpServeletResponse {
    private static MimetypesFileTypeMap mft = new MimetypesFileTypeMap();
    private Socket socket;
    private int statusCode = 200;
    private String statusReason = "OK";
    Map<String,String> headers = new HashMap<>();
    private File contentFile;

    public HttpServeletResponse(Socket socket) {
        this.socket = socket;
    }
    public void response() throws IOException {
        sendStatusLine();
        sendHeaders();
        sendContent();
    }

    private void sendContent() throws IOException {
       OutputStream out = socket.getOutputStream();
       if (contentFile!=null){
           FileInputStream fis = new FileInputStream(contentFile);
           int length;
           byte[] bur = new byte[1024*10];
           while ((length = fis.read(bur))!=-1){
               out.write(bur,0,length);
           }
       }

    }

    private void sendHeaders() throws IOException {
        Set<Map.Entry<String,String>> entrySet = headers.entrySet();
        for (Map.Entry<String,String> e : entrySet){
            String key = e.getKey();
            String value = e.getValue();
            System.out.println(key+": "+value);
        }
//        println("Content-Type: text/html");
//        println("Content-Length: "+contentFile.length());
        println("");
    }

    private void sendStatusLine() throws IOException {
        println("HTTP/1.1 "+ statusCode + " "+statusReason);
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);
        out.write(10);
    }
    public void addHeasers(String name,String value){
        headers.put(name,value);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        addHeasers("Content-Type",mft.getContentType(contentFile));
        addHeasers("Content-Length",contentFile.length()+"");
    }
}
